package be.jhd.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import be.jhd.domain.Application;
import be.jhd.domain.SpringValidationResponse;
import be.jhd.domain.ValidationResponse;

@Controller
public class ApplicationController {
	
	Logger LOG = LoggerFactory.getLogger(ApplicationController.class);

	@RequestMapping(value="/applicationForm.htm", method=RequestMethod.GET)
	public String showForm(Model model){
		model.addAttribute("application", new Application());
		return "applicationForm";
	}
	
	@RequestMapping(value="/applicationForm.htm", method=RequestMethod.POST)
	public String submitForm(@ModelAttribute(value="application") @Valid Application application, BindingResult result){
		return "applicationForm";
	}
	
	@RequestMapping(value="/applicationForm.json", method=RequestMethod.POST)
	public @ResponseBody ValidationResponse validateForm(@ModelAttribute(value="application") @Valid Application application, BindingResult result){
		
		ValidationResponse response = SpringValidationResponse.getInstance(result);
		
		if(response.isFailed()){
			LOG.error("Form failed");
		}
		
		return response;
	}
	
}
